import { defineStore } from 'pinia';
import Cookies from 'js-cookie';
import { Session } from '/@/utils/storage';
import {useSysAuthApi} from "/@/api/sysAuth";
import {SysGenderEnum} from "/@/types/eunm";

export const ACCOUNT_NAME = "account";

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosState => ({
		userInfos: {
			userName: '',
			photo: '',
			time: 0,
			roles: [],
			authBtnList: [],
		},
	}),
	actions: {
		async setUserInfos() {
			// 存储用户信息到浏览器缓存
			if (Session.get('userInfo')) {
				this.userInfos = Session.get('userInfo');
			} else {
				const userInfos = <UserInfos>await this.getApiUserInfo();
				this.userInfos = userInfos;
			}
		},
		async getApiUserInfo() {
			return new Promise(async (resolve) => {
				const userName = Cookies.get(ACCOUNT_NAME);
				const res = await useSysAuthApi().getUserInfo();
				const userInfo = res.data.result;

				// 用户信息模拟数据
				const userInfos = Object.assign({...userInfo}, {
					userName: userName,
					photo:
						userInfo.sex == 1
							? 'https://img2.baidu.com/it/u=1978192862,2048448374&fm=253&fmt=auto&app=138&f=JPEG?w=504&h=500'
							: 'https://img2.baidu.com/it/u=2370931438,70387529&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
					time: new Date().getTime(),
					roles: null,
					authBtnList: res.data.result.permissions,
				}) ;
				Session.set('userInfo', userInfos);
				resolve(userInfos);
			});
		},
	},
});
